package com.lkm.app_ui.m.Imple.hsj522;

import android.os.Handler;

import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.log.SystemLogger;
import com.lkm.app_ui.m.nfc.NFC_Module;
import com.lkm.comlib.task2.DefaultTaskExecutor;
import com.lkm.frame.entity.ResponEntityAbs;
import com.lkm.frame.task.ProgressDataImpl;
import com.lkm.frame.task2.BackCallAdapter;
import com.lkm.frame.task2.Task;
import com.lkm.frame.task2.TaskAdapter;
import com.lkm.javatool.StringHelp;



class LoopCardInOutTask extends TaskAdapter<Void, String, Void> {

    private NFC_Module hsj800tModule;

    private Handler handler;

    public LoopCardInOutTask(String id, NFC_Module hsj800tModule) {
        super(new DefaultTaskExecutor(AppConst.getTaskExecutor(), true), id, AppConst.getTaskManager2());
        handler = new Handler();
        this.hsj800tModule = hsj800tModule;
    }

    @Override
    public void doExecuting(Void param) {
        super.doExecuting(param);
        xx();
    }


    private String preCardNO = "";

    private boolean preHasCard = false;

    private void xx() {

        Task stringTask = hsj800tModule.tryReadCardNum();
        if (stringTask != null) {

            stringTask.addBackCall(new BackCallAdapter<Object, ResponEntityAbs<String>>() {
                @Override
                protected void onEnd(Task<?, Object, ResponEntityAbs<String>> task, ResponEntityAbs<String> re, boolean isCancel) {
                    super.onEnd(task, re, isCancel);

                    if (!getIsContinue()) return;

                    if(re == null){
                        SystemLogger.log("卡号 取消");
                    }else if( re.isSuccess()){

                    }else {

                    }
                    String o = re==null?"":re.getData();
                    onRe(o);
                    dexx();
                }
            });
            if (stringTask.execTask() == serialNum_not) {
                dexx();
            }
        } else {
            dexx();
        }


    }
    protected void onRe(String o){



        if (!StringHelp.isEmpty(o) && !StringHelp.equals(preCardNO, o)) {

            preHasCard = false;
        }
        preCardNO = o;
        if (StringHelp.isEmpty(o)) {
            if (preHasCard) {

                onCardOut();
            }
            preHasCard = false;
        } else {

            if (!preHasCard) {
                preHasCard = true;
                onCardIn(o);
            }
        }
    }

    private void onCardOut() {
    }

    private void onCardIn(String cardNo) {
        progressUpdate(new ProgressDataImpl<>(0, 0, cardNo));

    }

    private void dexx() {
        handler.removeCallbacksAndMessages(null);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (getIsContinue())
                    xx();
            }
        }, 300);

    }
}
